import "dart:developer";

import 'package:get/get.dart';
import 'package:ball_lion/entity/match/match_live_entity.dart';
import 'package:ball_lion/entity/match/odds_company_entity.dart';
import 'package:ball_lion/entity/my/expert/expert_apply_entity.dart';
import 'package:ball_lion/entity/other/app_update_entity.dart';
import 'package:ball_lion/entity/other/config_entity.dart';
import 'package:ball_lion/entity/other/resource_entity.dart';
import 'package:ball_lion/module/navigation/navigation_logic.dart';
import 'package:ball_lion/entity/home/search/search_entity.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/server/http/dio_utils.dart';
import 'package:ball_lion/server/http/request_header.dart';
import 'package:ball_lion/utils/app_config.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import '../api_dir.dart';

class OtherApi {
  static Future<List<ResourceEntity>?> getAppList(String id,
      {int? receiveTimeout}) async {
    final params = {"id": id};
    try {
      final result = await DioUtils.post("/resource/app-do/list/batch",
          params: params, receiveTimeout: receiveTimeout);
      if (result.statusCode == 200 && result.data["c"] == 200) {
        return (result.data["d"] as List)
            .map((e) => ResourceEntity.fromJson(e))
            .toList();
      } else {
        return null;
      }
    } catch (e) {
      return null;
    }
  }

  ///用户配置查询
  static Future<List<ConfigEntity>?> getConfigList(List<int> typeList) async {
    final params = {"typeList": typeList, "userId": User.auth?.userId};
    final result = await DioUtils.post("/${ApiDir.user}/usr-do/configList",
        params: params);
    // log("get config list $result");
    if (result.statusCode == 200 && result.data["c"] == 200) {
      return result.data["d"]
          .map<ConfigEntity>((e) => ConfigEntity.fromJson(e))
          .toList();
    }
    return null;
  }

  ///赔率公司列表
  static Future<List<OddsCompanyEntity>?> getOddsCompany() async {
    final result =
        await DioUtils.post("/${ApiDir.odds}/app-odds-do/oddsCompany");
    if (result.statusCode == 200 && result.data["c"] == 200) {
      List<OddsCompanyEntity> data = result.data["d"]
          .map<OddsCompanyEntity>((e) => OddsCompanyEntity.fromJson(e))
          .toList();
      return data;
    }
    return null;
  }

  ///视频直播源
  static Future<List<MatchLiveEntity>?> getVideoList(
      int matchId, int sportsId, String? liveId,
      {bool needLoading = false}) async {
    final params = {
      "matchId": matchId,
      "sportsId": sportsId,
    };
    final result = await DioUtils.post("/${ApiDir.info}/info-video-do/list",
        params: params, showLoading: needLoading, showToast: true);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      List<MatchLiveEntity> data = result.data["d"]
          .map<MatchLiveEntity>((e) => MatchLiveEntity.fromJson(e))
          .toList();
      return data;
    } else if (result.data["c"] == 1001) {
      if (liveId.hasValue) {
        // Get.dialog(const QsDialog.single("主播暂未开始直播，请耐心等待"));
      } else {
        // Toast.text(result.data["m"]);
      }
    }
    return null;
  }

  ///用户配置更新
  static Future<int?> setConfigList(
      List<ConfigEntity> config, String userId, int userType) async {
    final dataList = config
        .map(
            (e) => {"config": e.config, "type": e.type, "typeName": e.typeName})
        .toList();
    final params = {"list": dataList, "userId": userId, "userType": userType};
    final result = await DioUtils.post("/${ApiDir.user}/usr-do/configUpdate",
        params: params);
    if (result.statusCode == 200) {
      return result.data["c"];
    }
    return null;
  }

  // ///视频直播源
  // static Future<List<MatchVideoEntity>?> getVideoList(int matchId, int sportsId,
  //     {bool needLoading = false}) async {
  //   final params = {
  //     "matchId": matchId,
  //     "sportsId": sportsId,
  //   };
  //   final result = await DioUtils.post("/${ApiDir.info}/info-video-do/list",
  //       params: params, showLoading: needLoading);
  //   if (result.statusCode == 200 && result.data["c"] == 200) {
  //     List<MatchVideoEntity> data = result.data["d"]
  //         .map<MatchVideoEntity>((e) => MatchVideoEntity.fromJson(e))
  //         .toList();
  //     return data;
  //   }
  //   return null;
  // }

  ///专家申请
  static Future<ExpertApplyEntity?> expertApply(ExpertApplyEntity data) async {
    final result = await DioUtils.post("/${ApiDir.plan}/app-expert-do/apply",
        params: data.toJson(), showLoading: true);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      return ExpertApplyEntity.fromJson(result.data["d"]);
    } else if (result.statusCode == 200 && result.data["c"] == 1001) {
      throw Exception(result.data["m"] ?? '');
    }
    return null;
  }

  ///专家申请查询
  static Future<ExpertApplyEntity?> expertApplyInfo() async {
    String userId = User.info!.id!;
    final params = {"id": userId};
    final result = await DioUtils.post(
        "/${ApiDir.plan}/app-expert-do/applyInfo",
        params: params,
        showLoading: true);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      return ExpertApplyEntity.fromJson(result.data["d"]);
    }
    return null;
  }

  static Future<AppUpdateEntity?> checkUpdate(String version) async {
    try {
      final r = await DioUtils.post("/resource/app-do/version", params: {
        "appId": RequestHeader.appid,
        "channelId": AppConfig.config.channel,
        "version": version
      });
      return AppUpdateEntity.fromJson(r.data["d"]);
    } catch (err) {
      return null;
    }
  }

  static Future<List<SearchEntity>> getSearch({int? type, String? text}) async {
    final params = {"type": type, "word": text};
    final result = await DioUtils.post(
        "/${ApiDir.info}/app-search/${type == null ? "index" : "query"}",
        params: params);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      List<SearchEntity> data = result.data["d"]
          .map<SearchEntity>((e) => SearchEntity.fromJson(e))
          .toList();
      return data;
    }
    return [];
  }

  static Future uploadEvent(String event, {Map<String, String>? params}) async {
    // String route = Get.currentRoute;
    // List<String> routeList = route.split('?');
    // if (routeList.isNotEmpty) {
    //   route = routeList.first;
    // } else {
    //   return;
    // }

    // if (Get.currentRoute == Routes.navigation && Get.previousRoute != "/") {
    //   try {
    //     route = Get.find<NavigationLogic>().currentRoute;
    //   } catch (e) {}
    // }

    // Map<String, String> json = {
    //   "event": event,
    //   "path": route,
    // };
    // if (params != null) {
    //   json.addAll(params);
    // }
    // try {
    //   final result = await DioUtils.post('/data/app-event', params: json);
    //   log(result.data.toString());
    // } catch (e) {}
  }
}
